<template>
	<div>
		<el-form :model="menu" ref="menuForm" :rules="rules" label-width="100px">
			<el-form-item label="菜单名:" prop="label">
				<el-input v-model="menu.label"></el-input>
			</el-form-item>

			<el-form-item label="路径:" prop="path">
				<el-input v-model="menu.path"></el-input>
			</el-form-item>

			<el-form-item label="图标:">
				<el-input v-model="menu.icon"></el-input>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" @click="onSubmit(menuForm)">确定</el-button>
			</el-form-item>
		</el-form>
	</div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { api } from '@/api/index'
import { ElMessage } from 'element-plus'
import { FormType } from '@/config/const'
const { RequestMenuAdd, RequestMenuEdit } = api
const menuForm = ref(null)
const menu = ref({ id: 0, label: '', path: '', icon: '' })
const rules = ref({
	name: [{ required: true, message: '请输入菜单名', trigger: 'blur' }],
	path: [{ required: true, message: '请输入路径', trigger: 'blur' }]
})
const emit = defineEmits(['update:modelValue', 'close'])
const props = defineProps({
	parentId: Number,
	type: String,
	currentMenu: Object
})

onMounted(() => {
	// 编辑
	if (props.type === FormType.EDIT) {
		console.log(' props.currentMenu ', props.currentMenu)
		menu.value = props.currentMenu
	}
})

//事件
const onSubmit = menuForm => {
	menuForm.validate(valid => {
		if (valid) {
			if (props.type === FormType.EDIT) {
				editMenu(menu.value)
			} else {
				addMenu(menu.value)
			}
		}
	})
}

/**
 * 添加菜单
 */
const addMenu = async m => {
	let menu = {
		parentId: props.parentId,
		nodeType: 0,
		menuName: m.label,
		path: m.path,
		icon: m.icon
	}
	let data = await RequestMenuAdd(menu)
	if (data.resultCode === 1) {
		ElMessage.success('添加成功 ')
	} else {
		ElMessage.error('添加失败')
	}
	emit('close')
	emit('update:modelValue', false)
}
/**
 * 编辑菜单
 */
const editMenu = async m => {
	let menu = {
		id: m.id,
		menuName: m.label,
		path: m.path,
		icon: m.icon
	}
	let data = await RequestMenuEdit(menu)
	if (data.resultCode === 1) {
		ElMessage.success('编辑成功 ')
	} else {
		ElMessage.error('编辑失败')
	}
	emit('close')
	emit('update:modelValue', false)
}
</script>

<style lang="scss" scoped></style>
